package com.example.zx.theline.zsjh;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.zx.theline.R;
import com.example.zx.theline.zsjh.pub.ZsrjhChaKanActivity;
import com.loopj.android.http.RequestParams;
import com.scu.miomin.shswiperefresh.core.SHSwipeRefreshLayout;
import com.scu.miomin.shswiperefresh.view.SHListView;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import GsonBean.CheckInfoBean;
import GsonBean.ZsrjhBean;
import Utils.BackHandlerHelper;
import Utils.DateUtil;
import app.MyApplication;
import base.BaseFragment;
import bean.SearchBean;
import network.BaseCallBack;
import network.NetWorkApi;
import network.ObjectHttpResponseHandler;
import Utils.MyToast;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import views.ZsjhSearchView;
import views.ZsrjhView;

/**
 * Created by Ren on 2017/7/24.
 * 正式日计划
 */

public class ZsrjhFragment extends BaseFragment implements View.OnClickListener {

    View contentView;

    SHSwipeRefreshLayout mSHSwipeRefreshLayout;
    SHListView mSHListView;
    List<ZsrjhBean.RowsBean> mList;
    SHListViewAdapter mSHListViewAdapter;
    ZsjhSearchView mSearchView;

    private TextView mFootTextView;

    private TextView leftTextView, prev, centerTextView, next, rightTextView;


    //是否批量操作
    boolean isGroupDone = false;

    //数据加载分页数据
    int pageNumber = 0;
    //每次加载10条数据
    int pageSize = 10;

    SearchBean mSearchBean;

    ZsrjhBean mZsrjhBean;
    public static boolean onStartRefresh = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = inflater.inflate(R.layout.fragment_zsrjh, container, false);
        mSHSwipeRefreshLayout = (SHSwipeRefreshLayout) contentView.findViewById(R.id.SHSwipeRefreshLayout);
        mSHListView = (SHListView) contentView.findViewById(R.id.SHListView);
        View FootView = inflater.inflate(R.layout.refresh_view, null);
        mFootTextView = (TextView) FootView.findViewById(R.id.title);
        mSearchView = (ZsjhSearchView) contentView.findViewById(R.id.zsjhsearchview);
        mSHSwipeRefreshLayout.setFooterView(FootView);

        leftTextView = (TextView) contentView.findViewById(R.id.leftTextView);
        prev = (TextView) contentView.findViewById(R.id.prev);
        centerTextView = (TextView) contentView.findViewById(R.id.centerTextView);
        next = (TextView) contentView.findViewById(R.id.next);
        rightTextView = (TextView) contentView.findViewById(R.id.rightTextView);


        InitData();
        initSearchView();
        InitListen();
        return contentView;
    }


    @Override
    protected void InitData() {
        //初始化工具栏
//        leftTextView.setText("批量操作");
        mList = new ArrayList<>();
        mSHListViewAdapter = new SHListViewAdapter();
        mSHListView.setAdapter(mSHListViewAdapter);


    }

    private void initSearchView() {

        prev.setText("上一日");
        next.setText("下一日");
        centerTextView.setText(DateUtil.getYearAndMonthAndDay(date));

        mSearchBean = new SearchBean();
        //初始化搜索条件，开始日期为当天
        mSearchBean.setKsrq(DateUtil.getYearAndMonthAndDay(date));
        //初始化搜索条件，结束日期为当天
        mSearchBean.setJsrq(DateUtil.getYearAndMonthAndDay(date));
        mSearchView.setDefaultDate(mSearchBean);

        mSearchView.setConfirmListener(new ZsjhSearchView.OnClick() {
            @Override
            public void onConfirmListener(SearchBean Util) {
                mSearchBean = Util;
                mSHSwipeRefreshLayout.startRefresh();
                RefreshAllDate(1, pageSize);
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.leftTextView:
                getActivity().finish();
                break;
            case R.id.rightTextView:
                if (mSearchView.getVisibility() == View.GONE) {
                    mSearchView.setVisibility(View.VISIBLE);
                } else {
                    mSearchView.setVisibility(View.GONE);
                }
                break;
            case R.id.prev:
                butPrev();
                break;
            case R.id.next:
                butNext();
                break;

        }
    }

    //按钮上一天事件
    public void butPrev() {
        date = DateUtil.getAfterDayDate(date, -1);
        setSearchBean();
        upDatedAndRefresh();
    }

    //按钮下一天事件
    public void butNext() {
        date = DateUtil.getAfterDayDate(date, 1);
        setSearchBean();
        upDatedAndRefresh();
    }

    //更新标题栏日期并刷新列表数据
    public void upDatedAndRefresh() {
        centerTextView.setText(DateUtil.getYearAndMonthAndDay(date));
        //刷新列表数据
        RefreshAllDate(1, pageSize);
    }

    //设置搜索日期
    private void setSearchBean() {
        mSearchBean.setKsrq(DateUtil.getYearAndMonthAndDay(date));
        mSearchBean.setJsrq(DateUtil.getYearAndMonthAndDay(date));
//        //将搜索数据同步更新带搜索view当中
        mSearchView.setDefaultDate(mSearchBean);
    }


    @Override
    protected void InitListen() {
        prev.setOnClickListener(this);
        next.setOnClickListener(this);
        leftTextView.setOnClickListener(this);
        rightTextView.setOnClickListener(this);
        mSHSwipeRefreshLayout.setOnRefreshListener(new SHSwipeRefreshLayout.SHSOnRefreshListener() {

            //下滑刷新 完成
            @Override
            public void onRefresh() {
                //下滑更新ListView内所有数据 包括高级查询在内   后三个参数分别为查询条件：施工日期 日计划号 相关单位编号
                RefreshAllDate(1, pageSize);

            }

            //上拉加载 完成
            @Override
            public void onLoading() {
                //加载更多数据
                LoadMoreDate();

            }

            /**
             * 监听下拉刷新过程中的状态改变
             * @param percent 当前下拉距离的百分比（0-1）
             * @param state 分三种状态{NOT_OVER_TRIGGER_POINT：还未到触发下拉刷新的距离；OVER_TRIGGER_POINT：已经到触发下拉刷新的距离；START：正在下拉刷新}
             */

            //下滑 刷新数据
            @Override
            public void onRefreshPulStateChange(float percent, int state) {
                switch (state) {
                    case SHSwipeRefreshLayout.NOT_OVER_TRIGGER_POINT:
                        mSHSwipeRefreshLayout.setRefreshViewText("下拉刷新");

                        break;
                    case SHSwipeRefreshLayout.OVER_TRIGGER_POINT:
                        mSHSwipeRefreshLayout.setRefreshViewText("松开刷新");

                        break;
                    case SHSwipeRefreshLayout.START:
                        mSHSwipeRefreshLayout.setRefreshViewText("正在刷新");

                        break;
                }
            }

            //上拉 加载更多数据
            @Override
            public void onLoadmorePullStateChange(float percent, int state) {
                switch (state) {
                    case SHSwipeRefreshLayout.NOT_OVER_TRIGGER_POINT:
                        mFootTextView.setText("上拉加载");
                        break;
                    case SHSwipeRefreshLayout.OVER_TRIGGER_POINT:
                        mFootTextView.setText("松开加载");
                        break;
                    case SHSwipeRefreshLayout.START:
                        mFootTextView.setText("正在加载...");
                        break;
                }
            }
        });

    }

    //页面第一次进入加载
    @Override
    protected void onFragmentFirstVisible() {
        super.onFragmentFirstVisible();
        LoadMoreDate();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (onStartRefresh) {
            RefreshAllDate(1, 10); //初始化数据
            onStartRefresh = false;
        }
    }

    //加载正式日计划数据，加载更多正式日计划数据
    public void LoadMoreDate() {
        pageNumber++;
        Map<String,String> map =new HashMap<>();
        map.put("pageNumber", String.valueOf(pageNumber));
        map.put("pageSize", String.valueOf(pageSize));
        map.put("loginDwId", MyApplication.getmLoginUser().getUserUnitId());
        map = setParams(map, mSearchBean);
        MyApplication.ShowWaitDialog(getContext());
        NetWorkApi.getZsrjhList(map, new BaseCallBack<ZsrjhBean>() {
                    @Override
                    public void Success(Call<ZsrjhBean> call, Response<ZsrjhBean> response) {
                        try {
                            mZsrjhBean = response.body();
                            if (mZsrjhBean.getMsg().equals("success") && mZsrjhBean.getRows().size() == 0) {
//                                MyToast.showToast("没有更多数据");
                            } else {
                                mList.addAll(mZsrjhBean.getRows());
                                mSHListViewAdapter.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                        MyApplication.HideWaitDialog();
                    }

                    @Override
                    public void Failure(Call<ZsrjhBean> call, Throwable t) {
                        MyToast.showFail();
                    }

                    @Override
                    public void onFinally() {
                        mSHSwipeRefreshLayout.finishLoadmore();
                    }
                }
        );

    }

    //更新当前加载的所有正式日计划数据
    public void RefreshAllDate(int pageNumber, int pageSize) {
        this.pageNumber = pageNumber;
        Map<String,String> map =new HashMap<>();
        map.put("pageNumber", "1");
        map.put("pageSize", String.valueOf(pageNumber * pageSize));
        map.put("loginDwId", MyApplication.getmLoginUser().getUserUnitId());
        map = setParams(map, mSearchBean);
        MyApplication.ShowWaitDialog(getContext());
        NetWorkApi.getZsrjhList(map, new BaseCallBack<ZsrjhBean>() {

                    @Override
                    public void Success(Call<ZsrjhBean> call, Response<ZsrjhBean> response) {
                        try {
                            mZsrjhBean = response.body();
                            if (mZsrjhBean.getMsg().equals("success")) {
                                mList = mZsrjhBean.getRows();
                                mSHListViewAdapter.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                        MyApplication.HideWaitDialog();
                    }

                    @Override
                    public void Failure(Call<ZsrjhBean> call, Throwable t) {
                        MyToast.showFail();
                    }

                    @Override
                    public void onFinally() {
                        mSHSwipeRefreshLayout.finishRefresh();
                    }
                }
        );
    }

    public Map<String,String> setParams(Map<String,String> map, SearchBean Bean) {
        if (Bean != null) {
            if (Bean.getLb() != null && !Bean.getLb().equals("")) {
                map.put("searchSgLb", mSearchBean.getLb());
            }
            if (Bean.getJhh() != null && !Bean.getJhh().equals("")) {
                map.put("searchBh", mSearchBean.getJhh());
            }
            if (Bean.getXm() != null && !Bean.getXm().equals("")) {
                map.put("searchXlMc", mSearchBean.getXm());
            }
            if (Bean.getDwhbmid() != null && !Bean.getDwhbmid().equals("")) {
//                if (!MyApplication.getmLoginUser().getUserUnitType().equals("sgb") && !MyApplication.getmLoginUser().getUserUnitType().equals("jgcs"))
                map.put("searchDwId", mSearchBean.getDwhbmid());
            }
            if (Bean.getKsrq() != null && !Bean.getKsrq().equals("")) {
                map.put("searchStartDate", mSearchBean.getKsrq());
            }
            if (Bean.getJsrq() != null && !Bean.getJsrq().equals("")) {
                map.put("searchEndDate", mSearchBean.getJsrq());
            }
            if (Bean.getZt() != null && !Bean.getZt().equals("")) {
                if (Bean.getZt().equals("已下达"))
                    map.put("searchState", "0");
                if (Bean.getZt().equals("已作废"))
                    map.put("searchState", "1");
                if (Bean.getZt().equals("可作废"))
                    map.put("searchState", "2");
            }
        }
        return map;
    }


    private class SHListViewAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder mViewHolder;
            if (convertView == null) {
                mViewHolder = new ViewHolder();
                convertView = View.inflate(getContext(), R.layout.adapter_zsrjh, null);
                mViewHolder.mZsrjhView = (ZsrjhView) convertView.findViewById(R.id.ZsrjhView);

                convertView.setTag(mViewHolder);
            } else {
                mViewHolder = (ViewHolder) convertView.getTag();
            }
            mViewHolder.mZsrjhView.setDate(mList.get(position));
            mViewHolder.mZsrjhView.hideZt();
            //B类防御 根据该计划类型是否为B类 判断是否显示
//            if(mList.get(position).getLb().equals("B")){
//                mViewHolder.mZsrjhView.showLayoutProtectB();
//            } else {
//                mViewHolder.mZsrjhView.hideLayoutProtectB();
//            }
            if (isGroupDone) {
//                mViewHolder.mZsrjhView.toGroupDone();
            } else {
//                mViewHolder.mZsrjhView.cancelGroupDone();
                mViewHolder.mZsrjhView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        MyApplication.ShowWaitDialog(getContext());
                        NetWorkApi.getCheckInfoData(mList.get(position).getBh(), new Callback<CheckInfoBean>() {
                                    @Override
                                    public void onResponse(Call<CheckInfoBean> call, Response<CheckInfoBean> response) {
                                        try {
                                            CheckInfoBean Bean = response.body();
                                            ZsrjhChaKanActivity.checkInfoBean = Bean;
                                            getContext().startActivity(new Intent(getContext(), ZsrjhChaKanActivity.class));
                                        } catch (Exception e) {
                                            MyToast.showFail();

                                        }
                                        MyApplication.HideWaitDialog();
                                    }

                                    @Override
                                    public void onFailure(Call<CheckInfoBean> call, Throwable t) {
                                        MyToast.showFail();

                                    }
                                }
                        );


                    }
                });
            }
            return convertView;
        }


    }

    class ViewHolder {

        ZsrjhView mZsrjhView;

    }


    @Override
    public boolean onBackPressed() {
        if (mSearchView.getVisibility() == View.VISIBLE) {
            mSearchView.setVisibility(View.GONE);
            return true;
        } else {
            return BackHandlerHelper.handleBackPress(this);
        }
    }
}
